package com.gateway.video.rtsp.server.handler.support;

import com.gateway.video.rtsp.server.VideoServerConstants;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.rtsp.RtspVersions;
import io.netty.util.concurrent.Promise;
import lombok.var;
import org.kohsuke.MetaInfServices;
import java.time.LocalDateTime;

@MetaInfServices(RtspRequest.class)
public class TeardownRtspRequest extends AbstractRtspRequest{
    @Override
    protected void doHanlder(ChannelHandlerContext ctx, HttpRequest request, Promise promise) {
        var response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.SERVER, VideoServerConstants.VIDEO_VERSION);
        response.headers().set(HttpHeaderNames.DATE, LocalDateTime.now());
        response.headers().set(VideoServerConstants.SESSION, request.headers().get(VideoServerConstants.SESSION));
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache");
        response.headers().set(VideoServerConstants.CSEQ, request.headers().get(VideoServerConstants.CSEQ));

        /* 接收到客户端关闭指令，去关闭我们当前的传输 */

        ctx.writeAndFlush(response, ctx.newPromise().addListener(future -> {
            if(future.isSuccess()) {
                promise.setSuccess(response);
            }else {
                promise.setFailure(future.cause());
            }
        }));
    }

    @Override
    public boolean isSupport(HttpRequest request) {
        return request.method().name().equals(RtspHttpMethod.TEARDOWN.name());
    }
}
